package com.wz.dhs.config;

import cn.hutool.core.date.StopWatch;
import com.wz.dhs.model.common.Search;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author xyb
 * @Description 日志打印切面
 * @since 9:37 2022/7/18
 */
@Component
@Slf4j
@Aspect
public class LogPrintAspect {

    @Pointcut("execution(* com.wz.dhs.controller..*.*(..))")
    public void printLog() {

    }

    @Around(value = "printLog()")
    public Object intercept(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Object[] args = joinPoint.getArgs();
        String[] paramsName = signature.getParameterNames();
        StringBuilder sb = new StringBuilder("request:[");
        if (args != null && paramsName != null && args.length > 0 && paramsName.length > 0) {
            for (int i = 0; i < paramsName.length; i++) {
                sb.append(" ").append(paramsName[i]).append(" = ").append(args[i]).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append("]");
        log.info(sb.toString());
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object result = joinPoint.proceed();
        stopWatch.stop();
        long cost = stopWatch.getTotalTimeMillis();
        log.info("[response:{}][cost:{}]", result, cost);
        return result;
    }

    private void handlerPage(ProceedingJoinPoint joinPoint) {
        Arrays.stream(joinPoint.getArgs()).forEach(var -> {
            if (var instanceof Search) {
                Search var1 = (Search) var;
                if (var1.getPageNum() != null) {
                    var1.setPageNum((var1.getPageNum() - 1) * var1.getPageSize());
                }

            }
        });
    }
}


